package com.fy.spring.controller;


import com.fy.spring.entities.CommonResult;
import com.fy.spring.entities.Payment;
import com.fy.spring.serivce.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 服务发现，启动类上加上@EnableDiscoveryClient注解
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        int res = paymentService.create(payment);
        return res > 0 ?
                new CommonResult(200, "插入数据库成功", res) :
                new CommonResult(444, "插入数据库失败", null);
    }


    @GetMapping(value = "/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") int id) {
        Payment payment = paymentService.getPaymentById(id);
        return null != payment ?
                new CommonResult(200, "查询数据成功" + serverPort, payment) :
                new CommonResult(444, "查询数据失败" + serverPort, null);
    }

    @GetMapping("discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(service -> {
            System.out.println("----service" + service);
        });
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getServiceId()
                    + "\t" + instance.getHost() +
                    "\t" + instance.getPort() +
                    "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

}
